package com.glela.api.push.jpush;

import com.glela.api.push.util.PushConfig;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 
 * @author houmf
 * @version 创建时间：2016年7月25日 下午3:34:58
 * @name 推送
 */
public class JPush {

	private String content = "sss";// 推送内容

	// private String title ;//推送标题

	private JPushClient jpush;

	/**
	 * 设置标题和内容
	 * 
	 * @param title
	 * @param content
	 */
	public void setTitleAndContent(String title, String content) {
		// this.title = title ;
		this.content = content;
	}

	/**
	 * 初始化设置极光账号
	 * 
	 * @param appKey
	 * @param masterSecret
	 */
	public JPush() {
		this.jpush = new JPushClient(PushConfig.masterSecret, PushConfig.appKey);
	}

	/**
	 * 执行调用后返回结果
	 * 
	 * @param payload
	 * @return -1 jpush为null ； 2 成功 ； 3失败
	 */
	public int sendPush(PushPayload payload) {
		int i = -1;
		//
		if (jpush == null) {
			return i;
		}
		try {
			jpush.sendPush(payload);
		} catch (APIConnectionException e) {
			i = 3;
			return i;
		} catch (APIRequestException e) {
			i = 3;
			return i;
		}
		i = 2;
		return i;
	}

	/**
	 * 指定个人用户，不指定平台推送
	 * 
	 * @param alias
	 * @return
	 */
	public PushPayload push_alias_alertWithTitle(String alias) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(alias))
				.setNotification(Notification.alert(content)).build();
	}

	/**
	 * 按照组别进行推送
	 * 
	 * @param tag
	 * @return
	 */
	public PushPayload push_tag_alertWithTitle(String tag) {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag(tag))
				.setNotification(Notification.alert(content)).build();
	}

	/**
	 * 发送全部平台全部用户，标题和内容
	 * 
	 * @return
	 */
	public PushPayload push_all_all_alertWithTitle() {
		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.all())
				.setNotification(Notification.alert(content)).build();
	}

	/**
	 * 发送全部平台全部用户，内容无标题
	 * 
	 * @return
	 */
	public PushPayload push_all_all_alert() {
		return PushPayload.alertAll(content);
	}

}
